<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\GzhTemplate as GzhTemplateModer;
use app\admin\model\DistributeTask;
use app\admin\model\OperationTask;
use app\admin\model\DistributeStatistics;
use app\admin\model\User;
use app\api\controller\Withdraw as WithdrawApi;
use app\admin\model\Payment;
use app\admin\model\Product;
use app\admin\model\TemplateImgLog;
use app\admin\model\Shop;
use app\admin\model\ShopPriceLog;
use app\admin\model\SArea;
use app\admin\model\UserAddress;
use app\admin\model\Withdraw;
use app\admin\model\DistributeTaskInvite;
use app\admin\model\ProductCategory;
use app\admin\model\TaskCategoryList;
use app\admin\model\Area;
use app\common\model\Config;
use app\admin\model\TaskScheduled;
use think\Db;
use think\exception\PDOException;
use think\Exception;
use think\Request;
use think\Session;
use fast\Date;

/**
 * 任务管理
 *
 * @icon   fa fa-list
 */
class GzhTemplate extends Backend
{

    protected $model = null;
    protected $group_id = null;
    protected $admin = null;
    protected $categorylist = [];
    protected $noNeedRight = ['selectpage'];

    public function _initialize()
    {
 
        parent::_initialize();
        $this->model = new GzhTemplateModer();
        $admin = Session::get('admin');
        $group_id = db('auth_group_access')->where(['uid'=>$admin['id']])->value('group_id');
        $this->group_id = $group_id;
        $this->admin = $admin;
        $this->assignconfig('group_id', $group_id);
        $this->view->assign('group_id', $group_id);
        $this->view->assign('admin', $admin);
    }


    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
            $list = $this->model->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $params['content'] = $this->request->post('editorValue');
        $params['add_time'] = time();
        $result = false;
        Db::startTrans();
        try {
            
            $result = $this->model->insert($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        
        $this->success();
    }

      /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['text'] = $this->request->post("editorValue");
            if ($params) {
           
                try {
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


      /**
     * 编辑
     */
    public function send_gzh_task($ids = null)
    {

        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->redirect('distribute_task_index');
            return;
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['content'] = $this->request->post("editorValue");
            if ($params) {
           
                try {
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $product_list = Product::where(['status'=>1,'is_sale'=>0])->group('title')->limit(500)->order('id desc')->select();
        foreach ($product_list as $k=>&$v) {
            if(!$v['title']){
                unset($product_list[$k]);
            }

        }

        $list = $this->model->select();

        $this->view->assign("product_list", $product_list);
        $this->view->assign("list", $list);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function get_send_gzh_task($ids = null)
    {

        $data = $this->request->request();

        $info =  $this->model->where('id',$data['template_id'])->find();


        $product_list = Product::where(['id'=>['in',$data['ids']]])->select();
        
        $html = '';
        foreach ($product_list as &$v) {
           $html .= '<section>
           <p style="margin-top: 20px;margin-bottom: 0px;padding: 0px;outline: 0px;max-width: 100%;clear: both;min-height: 1em;visibility: visible;box-sizing: border-box !important;overflow-wrap: break-word !important">
               <strong style=";padding: 0px;outline: 0px;max-width: 100%;box-sizing: border-box !important;overflow-wrap: break-word !important;visibility: visible"><em style=";padding: 0px 15px;outline: 0px;max-width: 100%;text-align: right;visibility: visible;box-sizing: border-box !important;overflow-wrap: break-word !important">'.$v['title'].'</em></strong>
           </p>
       </section><br/>';
            $html .= '<section><p style="margin-top: 0px;margin-bottom: 0px;padding: 0px;outline: 0px;max-width: 100%;clear: both;min-height: 1em;font-size: 16px;visibility: visible;box-sizing: border-box !important;overflow-wrap: break-word !important">
            兑换积分：'.$v['price'].'</p></section>';

            $html .= '<section><img class="rich_pages wxw-img" src="'.$v['video_img'].'" alt="图片" style="margin-top: 20px;padding: 0px;outline: 0px;border: 0px;vertical-align: bottom;box-sizing: border-box !important;overflow-wrap: break-word !important;visibility: visible !important;width: 661px !important"/></section>';

        }
        $text = $info['text'];
        $text = str_replace('$content',$html,$text);
        $this->success('操作成功','',$text);
        dd($data);

        $row =1;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['content'] = $this->request->post("editorValue");
            if ($params) {
           
                try {
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $product_list = Product::where(['status'=>1,'is_sale'=>0])->group('title')->limit(500)->order('id desc')->select();
        foreach ($product_list as $k=>&$v) {
            if(!$v['title']){
                unset($product_list[$k]);
            }

        }

        $list = $this->model->select();

        $this->view->assign("product_list", $product_list);
        $this->view->assign("list", $list);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    

    /**
     * 查看
     */
    public function distribute_task_index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
            $list = Product::where($where)
                ->where(['is_sale'=>0,'status'=>1])
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }


    



}